<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="3d-model-placeholder"></div>
    </div>

    <!-- 登录卡片 -->
    <div class="login-card">
      <div class="login-header">
        <div class="logo">
          <el-icon :size="36" class="logo-icon">
            <OfficeBuilding />
          </el-icon>
          <h1>数字园区管理系统</h1>
        </div>
        <p class="slogan">数字化园区，智能化管理</p>
      </div>

      <el-form ref="loginFormRef" :rules="loginRules" :model="loginForm" class="login-form">
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" placeholder="请输入手机号" prefix-icon="User" :autocomplete="false" clearable
            size="large"></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" clearable
            show-password :show-password="showPassword" @input="handlePasswordInput" size="large"></el-input>
        </el-form-item>

        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input v-model="loginForm.captcha" placeholder="请输入验证码" prefix-icon="Picture" size="large"
              clearable></el-input>
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaUrl" alt="验证码" />
            </div>
          </div>
        </el-form-item>

        <div class="form-actions" v-if="false">
          <el-checkbox v-model="loginForm.rememberMe" class="remember-me">
            记住密码
          </el-checkbox>
          <!-- 2025年8月28日16:57:15，先隐藏，不完善功能，后面需要的时候再来完善
          <el-link type="primary" class="forgot-password" @click="handleForgotPassword">
            忘记密码?
          </el-link> -->
        </div>

        <el-button type="primary" ref="loginBtn" class="login-button" size="large" :loading="loading"
          @click="handleLogin">
          登录
        </el-button>
      </el-form>

      <!-- 底部信息 -->
      <div class="footer-info">
        <p>© 2025 数字园区管理系统 版权所有</p>
        <div class="footer-links">
          <el-link type="text" size="small">使用条款</el-link>
          <el-link type="text" size="small">隐私政策</el-link>
          <el-link type="text" size="small">帮助中心</el-link>
        </div>
      </div>

    </div>

    <!-- 忘记密码对话框 -->
    <!-- <el-dialog title="找回密码" v-model="showForgotDialog" :close-on-click-modal="false" width="400px">
      <el-form ref="forgotFormRef" :rules="forgotRules" :model="forgotForm" class="forgot-form">
        <el-form-item prop="email">
          <el-input v-model="forgotForm.email" placeholder="请输入注册邮箱" prefix-icon="Message" size="large"
            clearable></el-input>
        </el-form-item>

        <el-form-item prop="verifyCode">
          <div class="captcha-container">
            <el-input v-model="forgotForm.verifyCode" placeholder="请输入验证码" prefix-icon="Key" size="large"
              clearable></el-input>
            <el-button type="text" :disabled="sendCodeDisabled" @click="sendVerifyCode">
              {{ sendCodeText }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForgotDialog = false">取消</el-button>
        <el-button type="primary" @click="handleResetPassword">下一步</el-button>
      </template>
</el-dialog> -->
  </div>
</template>

<script setup>
import request from '@/api/request';
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus';
import auth from '@/components/utils/auth';
import { encryptPassword } from '@/components/utils/rsaEncrypt';

const loginBtn = ref(null);

// 监听全局回车键
const handleGlobalEnter = (e) => {
  if (e.key === 'Enter') {
    // 手动触发按钮的点击事件
    loginBtn.value?.$el?.click();
  }
};

// 获取路由实例
const router = useRouter()
const route = useRoute()
// 获取跳转参数，默认跳转到首页
const redirectPath = route.query.redirect || '/'
// 表单数据
const loginForm = ref({
  phone: '',
  password: '',
  captcha: '',
  rememberMe: false
});

// 找回密码表单
const forgotForm = ref({
  email: '',
  verifyCode: ''
});

// 状态管理
const loading = ref(false);
const showPassword = ref(false);
const captchaUrl = ref('');
const showForgotDialog = ref(false);
const sendCodeDisabled = ref(false);
const sendCodeText = ref('发送验证码');
const passwordStrength = ref(0); // 0-未输入 1-弱 2-中 3-强

// 表单验证规则
const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { length: 4, message: '验证码长度为 4 个字符', trigger: 'blur' }
  ]
};
const forgotRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { length: 6, message: '验证码长度为 6 个字符', trigger: 'blur' }
  ]
};

// 表单引用
const loginFormRef = ref(null);
const forgotFormRef = ref(null);

// 密码强度检测
const handlePasswordInput = (value) => {
  if (!value) {
    passwordStrength.value = 0;
    return;
  }

  let strength = 0;
  // 长度检测
  if (value.length >= 8) strength++;
  // 包含数字
  if (/[0-9]/.test(value)) strength++;
  // 包含字母
  if (/[a-zA-Z]/.test(value)) strength++;
  // 包含特殊字符
  if (/[^a-zA-Z0-9]/.test(value)) strength++;

  passwordStrength.value = strength;
};
import { v4 as uuidv4 } from 'uuid';
const uuid = uuidv4()
// 刷新验证码
const refreshCaptcha = async () => {
  // 实际项目中应该调用后端接口生成新的验证码
  try {
    // 关键：指定 responseType 为 blob
    const blob = await request.get('captcha/generate', {
      responseType: 'blob',  // 声明响应为二进制流
      params: {
        uuid: uuid
      }
    });

    // 将 blob 转换为可在 img 中显示的 URL
    captchaUrl.value = URL.createObjectURL(blob);
  } catch (error) {
    console.error('获取验证码失败：', error);
  }
};

// 发送验证码
const sendVerifyCode = () => {
  // 验证邮箱格式
  if (!forgotForm.email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(forgotForm.email)) {
    ElMessage.error('请输入正确的邮箱');
    return;
  }

  // 模拟发送验证码倒计时
  let count = 60;
  sendCodeDisabled.value = true;
  sendCodeText.value = `${count}s后重发`;

  const timer = setInterval(() => {
    count--;
    sendCodeText.value = `${count}s后重发`;

    if (count <= 0) {
      clearInterval(timer);
      sendCodeDisabled.value = false;
      sendCodeText.value = '发送验证码';
    }
  }, 1000);

  // 实际项目中应该调用后端接口发送验证码
  ElMessage.success('验证码已发送到您的邮箱');
};

// 处理登录
const handleLogin = async () => {
  try {
    // 表单验证
    await loginFormRef.value.validate();
    const phone = loginForm.value.phone;
    const password = loginForm.value.password;
    const captcha = loginForm.value.captcha;
    if (captcha.length != 4) {
      ElMessage.error('验证码长度不正确');
      return
    }
    //有明文存储密码风险
    const rememberMe = loginForm.value.rememberMe;
    if (rememberMe) {
      //存储账号密码
      localStorage.setItem('phone', phone);
      localStorage.setItem('password', password);
    } else {
      localStorage.removeItem('phone')
      localStorage.removeItem('password')
    }
    // 显示加载状态
    loading.value = true;
    try {

      // 1. 用 RSA 公钥加密密码
      const encryptedPwd = encryptPassword(password);
      if (!encryptedPwd) {
        alert('密码加密失败');
        return;
      }
      // 2. 提交登录请求（传输加密后的密码）
      const response = await request.post('auth/login', {
        phone: phone, // 实际项目中从输入框获取
        password: encryptedPwd, // 加密后的密码
        captcha: captcha,
        uuid: uuid
      }, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
      );

      if (response.success) {
        auth.setUserInfo(response.data)
        // 使用上面的redirectPath进行跳转，可以实现从哪个页面到登陆页的，登陆后回到哪个页面
        router.push(redirectPath);
      } else {
        ElMessage.error('登录失败:' + response.message);
        if (response.message === '登录失败：验证码已过期或者输入错误') {
          refreshCaptcha()
        }
      }
      loading.value = false;
    } catch (error) {
      loading.value = false;
      console.error('登录失败：', error);
      ElMessage.error('登录失败');
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error('登录表单验证失败');
  }
};

// 处理忘记密码
const handleForgotPassword = () => {
  showForgotDialog.value = true;
};

// 处理密码重置
const handleResetPassword = async () => {
  try {
    await forgotFormRef.value.validate();
    // 实际项目中应该调用后端接口验证并重置密码
    ElMessage.success('验证成功，即将跳转到密码重置页面');
    showForgotDialog.value = false;
  } catch (error) {
    console.error('找回密码表单验证失败:', error);
  }
};
// 页面加载时初始化
onMounted(() => {
  //显示验证码
  refreshCaptcha();
  // 从本地存储加载记住的用户名
  const savedPhone = localStorage.getItem('phone');
  if (savedPhone) {
    loginForm.value.phone = savedPhone;
  }
  const savedPassword = localStorage.getItem('password');
  if (savedPassword) {
    loginForm.value.password = savedPassword;
  }
  document.addEventListener('keyup', handleGlobalEnter);
});
// 组件卸载时移除监听（避免内存泄漏）
onUnmounted(() => {
  document.removeEventListener('keyup', handleGlobalEnter);
});
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  position: relative;
  overflow: hidden;
  padding: 20px;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
  background-image: url("@/assets/background.png");
}

.circle {
  position: absolute;
  border-radius: 50%;
  filter: blur(100px);
  opacity: 0.3;
}

.circle-1 {
  width: 600px;
  height: 600px;
  background: linear-gradient(135deg, #4096ff, #7cb305);
  top: -300px;
  right: -100px;
  animation: float 15s ease-in-out infinite;
}

.circle-2 {
  width: 500px;
  height: 500px;
  background: linear-gradient(135deg, #1890ff, #647bff);
  bottom: -250px;
  left: -150px;
  animation: float 18s ease-in-out 2s infinite;
}


.login-card {
  width: 100%;
  max-width: 420px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  padding: 36px 24px;
  z-index: 1;
  transition: all 0.3s ease;
}

.login-card:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
  transform: translateY(-5px);
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 12px;
}

.logo-icon {
  color: #165dff;
}

.login-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
  margin: 0;
}

.slogan {
  color: #86909c;
  font-size: 14px;
  margin: 0;
}

.login-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.captcha-image {
  width: 150px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  background-color: #f2f3f5;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.remember-me {
  color: #4e5969;
  font-size: 14px;
}

.forgot-password {
  font-size: 14px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(90deg, #165dff 0%, #0fc6c2 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: linear-gradient(90deg, #0e4cd8 0%, #0db8b5 100%);
  transform: translateY(-2px);
}

.other-login-options {
  margin-top: 24px;
  text-align: center;
}

.other-login-options span {
  display: inline-block;
  color: #86909c;
  font-size: 14px;
  margin-bottom: 16px;
  position: relative;
}

.other-login-options span::before,
.other-login-options span::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 60px;
  height: 1px;
  background-color: #e5e6eb;
}

.other-login-options span::before {
  left: -70px;
}

.other-login-options span::after {
  right: -70px;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 24px;
}

.social-icon {
  color: #86909c;
  cursor: pointer;
  transition: all 0.3s ease;
}

.social-icon:hover {
  color: #165dff;
  transform: scale(1.2);
}

.footer-info {
  margin-top: 30px;
  text-align: center;
  z-index: 1;
}

.footer-info p {
  color: #86909c;
  font-size: 12px;
  margin: 0 0 10px 0;
}

.footer-links {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.forgot-form {
  width: 100%;
}

/* 动画效果 */
@keyframes float {
  0% {
    transform: translateY(0px);
  }

  50% {
    transform: translateY(-30px);
  }

  100% {
    transform: translateY(0px);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .login-card {
    padding: 24px 16px;
  }

  .other-login-options span::before,
  .other-login-options span::after {
    width: 40px;
  }

  .other-login-options span::before {
    left: -50px;
  }

  .other-login-options span::after {
    right: -50px;
  }
}
</style>